package com.bytic.miaosha.service.impl;

import com.bytic.miaosha.domain.MiaoshaOrder;
import com.bytic.miaosha.domain.MiaoshaUser;
import com.bytic.miaosha.domain.OrderInfo;
import com.bytic.miaosha.mapper.OrderMapper;
import com.bytic.miaosha.redis.OrderKey;
import com.bytic.miaosha.service.OrderService;
import com.bytic.miaosha.service.RedisService;
import com.bytic.miaosha.vo.GoodsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RedisService redisService;

    @Override
    public MiaoshaOrder getMiaoshaOrderByUserIdGoodsId(long userId, long goodsId) {
        return redisService.get(OrderKey.miaoshaOrder, "" + userId + "_" + goodsId, MiaoshaOrder
                .class);
    }

    /**
     * 下订单  写入秒杀订单
     * @param user 秒杀用户
     * @param goods 商品信息
     * @return
     */
    @Override
    @Transactional
    public OrderInfo createOrder(MiaoshaUser user, GoodsVO goods) {
        // 下订单
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setDeliveryAddrId(0L);
        orderInfo.setGoodsCount(1);
        orderInfo.setGoodsId(goods.getId());
        orderInfo.setGoodsName(goods.getGoodsName());
        orderInfo.setGoodsPrice(goods.getMiaoshaPrice());
        orderInfo.setOrderChannel(1);
        orderInfo.setStatus(0);
        orderInfo.setUserId(user.getId());
        orderMapper.insertOrder(orderInfo);
        // 写入秒杀订单
        MiaoshaOrder miaoshaOrder = new MiaoshaOrder();
        miaoshaOrder.setGoodsId(goods.getId());
        miaoshaOrder.setOrderId(orderInfo.getId());
        miaoshaOrder.setUserId(user.getId());
        orderMapper.insertMiaoshaOreder(miaoshaOrder);
        redisService.set(OrderKey.miaoshaOrder, "" + user.getId() + "_" + goods.getId(), miaoshaOrder);
        return orderInfo;
    }

    @Override
    public OrderInfo getOrderById(long orderId) {
        return orderMapper.getOrderById(orderId);
    }
}
